// Copyright 2024 Antrea Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cluster

import (
	"context"
	"fmt"
	"strings"

	"github.com/blang/semver"
)

type checkK8sVersion struct{}

func init() {
	RegisterTest("check-k8s-version", &checkK8sVersion{})
}

func (t *checkK8sVersion) Run(ctx context.Context, testContext *testContext) error {
	discoveryClient := testContext.client.Discovery()
	serverVersion, err := discoveryClient.ServerVersion()
	if err != nil {
		return fmt.Errorf("error getting server version: %w", err)
	}
	currentVersion, err := semver.Parse(strings.TrimPrefix(serverVersion.GitVersion, "v"))
	if err != nil {
		return fmt.Errorf("error parsing server version: %w", err)
	}
	minVersion := semver.MustParse("1.23.0")
	if currentVersion.GTE(minVersion) {
		testContext.Log("Kubernetes server version is compatible with Antrea. Kubernetes version: %s", serverVersion.GitVersion)
	} else {
		return fmt.Errorf("Kubernetes min version required: %s", minVersion.String())
	}
	return nil
}
